package com.hb.unic.core.util;

import java.net.InetAddress;

import lombok.SneakyThrows;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 混合的工具类
 *
 * @since v1.0，2023/8/31 23:03，create by Mr.Huang.
 */
public class RequestUtils {

    /**
     * 获取服务器名
     * 
     * @return 服务器名
     */
    @SneakyThrows
    public static String getServiceName() {
        return InetAddress.getLocalHost().getHostName();
    }

    /**
     * 获取服务器ip
     * 
     * @return 服务器ip
     */
    @SneakyThrows
    public static String getServiceIp() {
        return InetAddress.getLocalHost().getHostAddress();
    }

    /**
     * 获取请求者ip地址
     *
     * @return ip地址
     */
    public static String getRequestIp() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return "";
        }
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        return IpUtils.getIpAddr(request);
    }

    /**
     * 获取请求者ip地址
     *
     * @return ip地址
     */
    public static String getRequestUri() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return "";
        }
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        return request.getRequestURI();
    }

}
